package com.burgeon.backend.EnterpriseWeChat.service.Impl;

import com.burgeon.backend.EnterpriseWeChat.entity.EWEmployee;
import com.burgeon.backend.EnterpriseWeChat.mappers.EWInfoMapper;
import com.burgeon.backend.EnterpriseWeChat.mappers.EWQyCodeMapper;
import com.burgeon.backend.EnterpriseWeChat.rest.EWEmployee.EWEmployeeIsInvite;
import com.burgeon.backend.EnterpriseWeChat.rest.EWEmployee.QueryEWEmployee;
import com.burgeon.backend.EnterpriseWeChat.service.EWInfoService;
import com.burgeon.backend.EnterpriseWeChat.service.EWelcomeService;
import com.burgeon.backend.EnterpriseWeChat.service.ex.UpDataException;
import com.burgeon.backend.EnterpriseWeChat.service.ex.UserNotFoundException;
import com.burgeon.backend.SHOPBACKEND.service.ex.UploadException;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Service
public class EWelcomeServiceImpl implements EWelcomeService {


    private final static Log logger = LogFactory.getLog(EWelcomeService.class);

    @Autowired
    private EWInfoService ewInfoService;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private EWQyCodeMapper ewQyCodeMapper;
    @Autowired
    private EWInfoMapper ewInfoMapper;




    @Override
    public EWEmployee GetOpenId(String code, String token, HttpSession session) throws UpDataException{
//        session.setAttribute("token",token);
        System.err.println("token================"+token);

        Info info = GetInfoByToken(token);
        if(null == token || token.isEmpty()){
            throw new UpDataException("token===="+token);
        }
        token = token.toLowerCase();
        System.err.println("转换token================"+token);
//        if(null == code || code.isEmpty()){
////            throw new UpDataException("code===="+code);
////        }
        //获取信息
        String ACCESS_TOKEN = ewInfoService.getAppAccessToken(token);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?" +
                "access_token="+ACCESS_TOKEN+"&js_code="+code+"&grant_type=authorization_code";
        logger.info("code===="+code);
        System.err.println(url);
        RestTemplate restTemplate = new RestTemplate();
        String str = restTemplate.getForObject(url, String.class);
        System.err.println(str);
        logger.info(str);

        String corpid = null;
        String userid = null;
        String session_key = null;
//        EWEmployee ewEmployee = new EWEmployee();

        QueryEWEmployee queryEWEmployee = new QueryEWEmployee(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            JSONObject jsonObject = new JSONObject(str);
            if("0".equals(jsonObject.getString("errcode"))) {
                corpid = jsonObject.getString("corpid");
                userid = jsonObject.getString("userid");
                session_key = jsonObject.getString("session_key");

//                session.setAttribute("corpid", corpid);
//                session.setAttribute("userid", userid);
//                session.setAttribute("session_key", session_key);
//                System.err.println(jsonObject);

                //先不提交
                EWEmployee ewEmployee = queryEWEmployee.getData(userid);
                if(null == ewEmployee){
                    logger.info("登录错误ewEmployee=="+ewEmployee+"code");
                    throw new UserNotFoundException("请先成为企业内部成员");
                }

                return ewEmployee;
            }else {
                logger.info(jsonObject.getString("errcode")+jsonObject.getString("errmsg"));
                throw new UserNotFoundException(jsonObject.getString("errcode"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("登录错误"+e.getMessage());
            throw new UserNotFoundException("登录错误:"+e.getMessage());
        }
//        return ewEmployee;
    }

    @Override
    public String QyCode( String qyCard,String token,String empId){
        System.err.println("empNo==========================="+empId);
        System.err.println("token==========================="+token);
//        String card = ewQyCodeMapper.getQyCardByEmpNo(empNo,token);
//        if (null == card) {
//            //文件名
//            String fileName = file.getOriginalFilename();
//            System.err.println(fileName);
//            // 后缀名
//            String suffixName = fileName.substring(fileName.lastIndexOf("."));
//            // 上传后的路径
//            String filePath = "//root//code//img//" + token + "//QyCode//" + empNo + "//";
//            // 新文件名
//            fileName = empNo + suffixName;
//            saveFile(file, fileName, filePath);
//            //上传的头像存到erp
//            card = "http://lfwd.cloudsmicro.com/img/" + token + "/QyCode/" + empNo + "/" +empNo+ fileName;
//            System.err.println("card================================================"+card);
            ewQyCodeMapper.createQyCard(qyCard, empId, token);
//        }
        return qyCard;
    }

    /**
     * 获取服务器地址
     * @param token
     * @return
     */
    @Override
    public String getWeChatUrl(String token) {
        token = token.toLowerCase();
        String url = ewInfoMapper.getWeChatUrl(token);
        return url;
    }

    @Override
    public String upCardUrl(MultipartFile file, String token, String empId) {
        String card = ewQyCodeMapper.getQyCardByEmpNo(empId,token);
        if (null == card) {
            //文件名
            String fileName = file.getOriginalFilename();
            System.err.println(fileName);
            // 后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            // 上传后的路径
            String filePath = "//root//code//img//" + token + "//QyCode//" + empId + "//";
            // 新文件名
            fileName = empId + suffixName;
            saveFile(file, fileName, filePath);
            //上传的头像存到erp
            card = "http://lfwd.cloudsmicro.com/img/" + token + "/QyCode/" + empId + "/" + empId + fileName;
            System.err.println("card================================================" + card);
            ewQyCodeMapper.createQyCard(card, empId, token);
        }
        return card;
    }

    //查询导购是否可用
    @Override
    public String IsActive(String id, String token) {
        Info info = GetInfoByToken(token);
        EWEmployeeIsInvite ewEmployeeIsInvite = new EWEmployeeIsInvite(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            String isInvite = ewEmployeeIsInvite.getData(id);
            if("null".equals(isInvite)){
                throw new UpDataException("请确认账号");
            }
            return isInvite;
        } catch (Exception e) {
            e.printStackTrace();
            throw  new UpDataException(e.getMessage());
        }

    }

    //保存文件
    private void saveFile(MultipartFile multipartFile, String fileName, String filePath) {
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("保存文件出错"+e.getMessage());
            throw new UploadException("系统错误");
        } catch (Exception e) {
            logger.error("保存文件出错"+e.getMessage());
            System.err.println(e.getMessage());
            throw new UploadException("系统错误");
        }
    }

    private Info GetInfoByToken(String token) {
        return accountMapper.GetTokenData(token);
    }
}
